﻿package lz.controls
{
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.ui.Keyboard;
	import flash.utils.Dictionary;
	
	import lz.controls.core.InvalidationType;
	import lz.controls.core.UIComponent;
	import lz.controls.listClasses.ICellRenderer;
	import lz.controls.listClasses.ListData;
	import lz.controls.managers.IFocusManagerComponent;
	
	/**
	 * List 组件将显示基于列表的信息，并且是适合显示信息数组的理想选择。
	 * List 组件由 item、row 和 data provider 构成，如下所述：
	 * Item：ActionScript 对象，通常包含 label 属性和 data 属性，前者是描述性的属性，后者用于存储与项目关联的数据。
	 * Row：用于显示项目的组件。
	 * Data provider：一个组件，用于模拟 List 组件所显示的项目。
	 * 默认情况下，List 组件使用 CellRenderer 类提供在其中显示列表项目的行。 
	 * 可以通过编程方式创建这些行；这通常通过细分 CellRenderer 类来完成。
	 *  CellRenderer 类实现 ICellRenderer 接口，该接口提供一组属性和方法，List 组件可以使用这些属性和方法对其中的行进行操作，并将数据和状态信息发送到各行以供显示。 
	 * 这将包括有关数据大小调整和选定内容的信息。
	 * List 组件提供针对其数据提供程序执行的方法，例如 addItem() 和 removeItem() 方法。
	 * 可以使用上述及其他方法操作同一帧中作为 List 组件存在的任何数组的数据，然后将更改广播给多个视图。
	 * 如果未随 List 组件提供外部数据提供程序，则这些方法会自动创建一个数据提供程序实例并通过 List.dataProvider 属性将其公开。
	 * List 组件将使用实现 ICellRenderer 接口的 Sprite 来呈现每一行。 若要指定此渲染器，请使用 List.cellRenderer 属性。 
	 * 您也可以创建一个 Array 实例或者从服务器上获取一个实例，然后将它用作多个列表、组合框、数据网格等的数据模型。
	 */
	public class List extends SelectableList implements IFocusManagerComponent
	{

		/**
         * 行高
		 */
		protected var _rowHeight:Number = 20;
		/**
         * 行渲染器
		 */
		protected var _cellRenderer:Object;
		/**
         * dataProvider 对象中的字段名称，该字段名称将显示为 TextInput 字段和下拉列表的标签。
		 */
		protected var _labelField:String="label";
		/**
         * 获得项的标签的函数。
		 */
		protected var _labelFunction:Function;
		/**
         *用于提供项的图标的项字段。
		 */
		protected var _iconField:String = "icon";
		/**
         *用于获得项的图标的函数。
		 */
		protected var _iconFunction:Function;
		
		/**
         * 默认样式
         */
		private static var defaultStyles:Object = {
													focusRectSkin:null,
													focusRectPadding:null
													};
        /**
         *  检索当前组件的默认样式映射。
         */
		public static function getStyleDefinition():Object
		{ 
			return mergeStyles(defaultStyles, SelectableList.getStyleDefinition());
		}
		/**
		 *  @private
		 *  Method for creating the Accessibility class.
         *  This method is called from UIComponent.
		 */
		public static var createAccessibilityImplementation:Function;
		/**
         *创建新的 List 组件实例。
		 */
		public function List() 
		{
			super();
		}
		/**
         * 获取或设置 dataProvider 对象中的字段名称，该字段名称将显示为 TextInput 字段和下拉列表的标签。
		 * 默认情况下，组件将显示各 dataProvider 项目的 label 属性。 如果 dataProvider 项目不包含 label 属性，则可以设置 labelField 属性以使用其他属性。
		 * 注意：labelField 属性不在 labelFunction 属性设置为回调函数时使用。
		 * 默认值为 "label"。
		 */
		public function get labelField():String 
		{
			return _labelField;
		}
		public function set labelField(value:String):void 
		{
			if (value == _labelField) { return; }
			_labelField = value;
			invalidate(InvalidationType.DATA);
		}
        /**
         *获取或设置用于获得项的标签的函数。
		 * 默认情况下，组件将显示 dataProvider 项目的 label 属性。 
		 * 但某些数据集可能没有 label 字段，或者没有不需修改其值即可用作标签的字段。
		 * 例如，某给定数据集可能存储了全名，但将全名分开保存在 lastName 和 firstName 字段中。 
		 * 在这种情况下，此属性可能用来设置一个回调函数，该函数将 lastName 和 firstName 字段的值连接在一起成为全名字符串以供显示。
		 * 注意：labelField 属性不在 labelFunction 属性设置为回调函数时使用。
		 * 默认值为 null。
		 */
		public function get labelFunction():Function
		{
			return _labelFunction;
		}
		public function set labelFunction(value:Function):void
		{
			if (_labelFunction == value) { return; }
			_labelFunction = value;
			invalidate(InvalidationType.DATA);
		}
		/**
         *获取或设置用于提供项的图标的项字段。
		 * 注意：iconField 不在 iconFunction 属性设置为回调函数时使用。
		 * 默认值为 "icon"。
		 */
		public function get iconField():String 
		{
			return _iconField;
		}
		public function set iconField(value:String):void 
		{
			if (value == _iconField) { return; }
			_iconField = value;
			invalidate(InvalidationType.DATA);
		}
		/**
		 * 获取或设置用于获得项的图标的函数。
		 * 注意：iconField 不在 iconFunction 属性设置为回调函数时使用。
		 * 默认值为 null。
		 */
		public function get iconFunction():Function 
		{
			return _iconFunction;
		}
		public function set iconFunction(value:Function):void 
		{
			if (_iconFunction == value) { return; }
			_iconFunction = value;
			invalidate(InvalidationType.DATA);
		}
		/**
		 * 获取或设置在列表中至少部分可见的行的行数。
		 */
		override public function get rowCount():uint 
		{
			//This is low right now (ie. doesn't count two half items as a whole):
			return Math.ceil(calculateAvailableHeight()/rowHeight);
		}
		public function set rowCount(value:uint):void 
		{
			var pad:Number = Number(getStyleValue("contentPadding"));
			var scrollBarHeight:Number = (_horizontalScrollPolicy == ScrollPolicy.ON || (_horizontalScrollPolicy == ScrollPolicy.AUTO && _maxHorizontalScrollPosition > 0)) ? 15 : 0;
			height = rowHeight*value+2*pad+scrollBarHeight;
		}
		/**
		 *获取或设置列表中每一行的高度，以像素为单位。
		 *默认值为 20。
		 */
		public function get rowHeight():Number
		{
			return _rowHeight;
		}
		public function set rowHeight(value:Number):void 
		{
			_rowHeight = value;
			invalidate(InvalidationType.SIZE);
		}
		/**
         *将列表滚动至位于指定索引处的项目。 如果索引超出范围，则滚动位置不发生变化。
		 * 参数
		 * newCaretIndex:int — 要滚动到的索引位置。
		 */
		override public function scrollToIndex(newCaretIndex:int):void 
		{
			drawNow();
			var lastVisibleItemIndex:uint = Math.floor((_verticalScrollPosition + availableHeight) / rowHeight) - 1;
			var firstVisibleItemIndex:uint = Math.ceil(_verticalScrollPosition / rowHeight);
			if(newCaretIndex < firstVisibleItemIndex) 
			{
				verticalScrollPosition = newCaretIndex * rowHeight;
			} else if(newCaretIndex > lastVisibleItemIndex) 
			{
				verticalScrollPosition = (newCaretIndex + 1) * rowHeight - availableHeight;
			}
		}
		/**
         * 配置UI
		 */
		override protected function configUI():void 
		{
			useFixedHorizontalScrolling = true;
			_horizontalScrollPolicy = ScrollPolicy.AUTO;
			_verticalScrollPolicy = ScrollPolicy.AUTO;
			
			super.configUI();
		}
		/**
         * 计算可见高度
		 */
		protected function calculateAvailableHeight():Number 
		{
			var pad:Number = Number(getStyleValue("contentPadding"));
			return height-pad*2-((_horizontalScrollPolicy == ScrollPolicy.ON || (_horizontalScrollPolicy == ScrollPolicy.AUTO && _maxHorizontalScrollPosition > 0)) ? 15 : 0);
		}
        /**
         * 设置水平滚动位置
		 */
		override protected function setHorizontalScrollPosition(value:Number,fireEvent:Boolean=false):void
		{
			list.x = -value;
			super.setHorizontalScrollPosition(value, true);
		}
        /**
         * 设置垂直滚动位置
		 */
		override protected function setVerticalScrollPosition(scroll:Number,fireEvent:Boolean=false):void 
		{
			// This causes problems. It seems like the render event can get "blocked" if it's called from within a callLater
			invalidate(InvalidationType.SCROLL);
			super.setVerticalScrollPosition(scroll, true);
		}
        /**
         * 画界面
		 */
		override protected function draw():void 
		{
			var contentHeightChanged:Boolean = (contentHeight != rowHeight*length);
			contentHeight = rowHeight*length;
			
			if (isInvalid(InvalidationType.STYLES)) 
			{
				setStyles();
				drawBackground();
				// drawLayout is expensive, so only do it if padding has changed:
				if (contentPadding != getStyleValue("contentPadding")) 
				{
					invalidate(InvalidationType.SIZE,false);
				}
				// redrawing all the cell renderers is even more expensive, so we really only want to do it if necessary:
				if (_cellRenderer != getStyleValue("cellRenderer"))
				{
					// remove all the existing renderers:
					_invalidateList();
					_cellRenderer = getStyleValue("cellRenderer");
				}
			}
			if (isInvalid(InvalidationType.SIZE, InvalidationType.STATE) || contentHeightChanged) 
			{
				drawLayout();
			}
			
			if (isInvalid(InvalidationType.RENDERER_STYLES)) 
			{
				updateRendererStyles();	
			}
			
			if (isInvalid(InvalidationType.STYLES,InvalidationType.SIZE,InvalidationType.DATA,InvalidationType.SCROLL,InvalidationType.SELECTED)) 
			{
				drawList();
			}
			
			// Call drawNow on nested components to get around problems with nested render events:
			updateChildren();
			
			// Not calling super.draw, because we're handling everything here. Instead we'll just call validate();
			validate();
		}
		/**
         * 画列表
		 */
		override protected function drawList():void 
		{
			// List is very environmentally friendly, it reuses existing 
			// renderers for old data, and recycles old renderers for new data.

			// set horizontal scroll:
			listHolder.x = listHolder.y = contentPadding;
			
			var rect:Rectangle = listHolder.scrollRect;
			rect.x = _horizontalScrollPosition;
			
			// set pixel scroll:
			rect.y = Math.floor(_verticalScrollPosition)%rowHeight;
			listHolder.scrollRect = rect;
			
			listHolder.cacheAsBitmap = useBitmapScrolling;
			
			// figure out what we have to render:
			var startIndex:uint = Math.floor(_verticalScrollPosition/rowHeight);
			var endIndex:uint = Math.min(length,startIndex + rowCount+1);
			
			
			// these vars get reused in different loops:
			var i:uint;
			var item:Object;
			var renderer:ICellRenderer;
			
			// create a dictionary for looking up the new "displayed" items:
			var itemHash:Dictionary = renderedItems = new Dictionary(true);
			for (i=startIndex; i<endIndex; i++) 
			{
				itemHash[_dataProvider.getItemAt(i)] = true;
			}
			
			// find cell renderers that are still active, and make those that aren't active available:
			var itemToRendererHash:Dictionary = new Dictionary(true);
			while (activeCellRenderers.length > 0) 
			{
				renderer = activeCellRenderers.pop() as ICellRenderer;
				item = renderer.data;
				if (itemHash[item] == null || invalidItems[item] == true)
				{
					availableCellRenderers.push(renderer);
				} else 
				{
					itemToRendererHash[item] = renderer;
					// prevent problems with duplicate objects:
					invalidItems[item] = true;
				}
				list.removeChild(renderer as DisplayObject);
			}
			invalidItems = new Dictionary(true);
			
			// draw cell renderers:
			for (i=startIndex; i<endIndex; i++)
			{
				var reused:Boolean = false;
				item = _dataProvider.getItemAt(i);
				if (itemToRendererHash[item] != null) 
				{
					// existing renderer for this item we can reuse:
					
					reused = true;
					renderer = itemToRendererHash[item];
					delete(itemToRendererHash[item]);
				} else if (availableCellRenderers.length > 0)
				{
					
					// recycle an old renderer:
					renderer = availableCellRenderers.pop() as ICellRenderer;
				} else 
				{
					
					// out of renderers, create a new one:
					renderer = getDisplayObjectInstance(getStyleValue("cellRenderer")) as ICellRenderer;
					var rendererSprite:Sprite = renderer as Sprite;
					if (rendererSprite != null)
					{
						rendererSprite.addEventListener(MouseEvent.CLICK,handleCellRendererClick,false,0,true);
						rendererSprite.addEventListener(MouseEvent.ROLL_OVER,handleCellRendererMouseEvent,false,0,true);
						rendererSprite.addEventListener(MouseEvent.ROLL_OUT,handleCellRendererMouseEvent,false,0,true);
						rendererSprite.addEventListener(Event.CHANGE,handleCellRendererChange,false,0,true);
						rendererSprite.doubleClickEnabled = true;
						rendererSprite.addEventListener(MouseEvent.DOUBLE_CLICK,handleCellRendererDoubleClick,false,0,true);
						
						if (rendererSprite.hasOwnProperty("setStyle")) 
						{
							for (var n:String in rendererStyles) 
							{
								rendererSprite["setStyle"](n, rendererStyles[n])
							}
						}
					}
				}
				list.addChild(renderer as Sprite);
				activeCellRenderers.push(renderer);
				
				renderer.y = rowHeight*(i-startIndex);
				renderer.setSize(availableWidth+_maxHorizontalScrollPosition,rowHeight);
				
				var label:String = itemToLabel(item);
				
				var icon:Object = null;
				if (_iconFunction != null) 
				{
					icon = _iconFunction(item);
				} else if (_iconField != null) 
				{
					icon = item[_iconField];
				}
				
				if (!reused) 
				{
					renderer.data = item;
				}
				renderer.listData = new ListData(label,icon,this,i,i,0);
				renderer.selected = (_selectedIndices.indexOf(i) != -1);
				
				// force an immediate draw (because render event will not be called on the renderer):
				if (renderer is UIComponent) 
				{
					(renderer as UIComponent).drawNow();
				}
			}
		}
        /**
         * 鼠标按下事件
		 */
		override protected function keyDownHandler(event:KeyboardEvent):void 
		{
			if (!selectable) { return; }
			switch (event.keyCode) 
			{
				case Keyboard.UP:
				case Keyboard.DOWN:
				case Keyboard.END:
				case Keyboard.HOME:
				case Keyboard.PAGE_UP:
				case Keyboard.PAGE_DOWN:
					moveSelectionVertically(event.keyCode, event.shiftKey && _allowMultipleSelection, event.ctrlKey && _allowMultipleSelection);
					break;
				case Keyboard.LEFT:
				case Keyboard.RIGHT:
					moveSelectionHorizontally(event.keyCode, event.shiftKey && _allowMultipleSelection, event.ctrlKey && _allowMultipleSelection);
					break;
				case Keyboard.SPACE:
					if(caretIndex == -1) 
					{
						caretIndex = 0;
					}
					doKeySelection(caretIndex, event.shiftKey, event.ctrlKey);
					scrollToSelected();
					break;
				default:
					var nextIndex:int = getNextIndexAtLetter(String.fromCharCode(event.keyCode), selectedIndex);
					if (nextIndex > -1) 
					{
						selectedIndex = nextIndex;
						scrollToSelected();
					}
					break;
			}
			event.stopPropagation();
		}

		/**
         * @private (protected)
		 * Moves the selection in a horizontal direction in response
		 * to the user selecting items using the left-arrow or right-arrow
		 * keys and modifiers such as  the Shift and Ctrl keys.
		 *
		 * <p>Not implemented in List because the default list
		 * is single column and therefore doesn't scroll horizontally.</p>
		 *
		 * @param code The key that was pressed (e.g. Keyboard.LEFT)
         *
		 * @param shiftKey <code>true</code> if the shift key was held down when
		 *        the keyboard key was pressed.
         *
		 * @param ctrlKey <code>true</code> if the ctrl key was held down when
         *        the keyboard key was pressed.
		 */
		override protected function moveSelectionHorizontally(code:uint, shiftKey:Boolean, ctrlKey:Boolean):void {}
		/**
         * @private (protected)
		 * Moves the selection in a vertical direction in response
		 * to the user selecting items using the up-arrow or down-arrow
		 * Keys and modifiers such as the Shift and Ctrl keys.
		 *
		 * @param code The key that was pressed (e.g. Keyboard.DOWN)
         *
		 * @param shiftKey <code>true</code> if the shift key was held down when
		 *        the keyboard key was pressed.
         *
		 * @param ctrlKey <code>true</code> if the ctrl key was held down when
         *        the keyboard key was pressed.
         *
		 */
		override protected function moveSelectionVertically(code:uint, shiftKey:Boolean, ctrlKey:Boolean):void 
		{
			var pageSize:int = Math.max(Math.floor(calculateAvailableHeight() / rowHeight), 1);
			var newCaretIndex:int = -1;
			var dir:int = 0;
			switch(code) 
			{
				case Keyboard.UP:
					if (caretIndex > 0)
					{
						newCaretIndex = caretIndex - 1;
					}
					break;
				case Keyboard.DOWN:
					if (caretIndex < length - 1) 
					{
						newCaretIndex = caretIndex + 1;
					}
					break;
				case Keyboard.PAGE_UP:
					if (caretIndex > 0) 
					{
						newCaretIndex = Math.max(caretIndex - pageSize, 0);
					}
					break;
				case Keyboard.PAGE_DOWN:
					if (caretIndex < length - 1) 
					{
						newCaretIndex = Math.min(caretIndex + pageSize, length - 1);
					}
					break;
				case Keyboard.HOME:
					if (caretIndex > 0) 
					{
						newCaretIndex = 0;
					}
					break;
				case Keyboard.END:
					if (caretIndex < length - 1) 
					{
						newCaretIndex = length - 1;
					}
					break;
			}
			if(newCaretIndex >= 0) 
			{
				doKeySelection(newCaretIndex, shiftKey, ctrlKey);
				scrollToSelected();
			}
		}
		
        /**
         * @private (protected)
		 */		
		protected function doKeySelection(newCaretIndex:int, shiftKey:Boolean, ctrlKey:Boolean):void
		{
			var selChanged:Boolean = false;
			if(shiftKey) 
			{
				var i:int;
				var selIndices:Array = [];
				var startIndex:int = lastCaretIndex;
				var endIndex:int = newCaretIndex;
				if(startIndex == -1)
				{
					startIndex = caretIndex != -1 ? caretIndex : newCaretIndex;
				}
				if(startIndex > endIndex) 
				{
					endIndex = startIndex;
					startIndex = newCaretIndex;
				}
				for(i = startIndex; i <= endIndex; i++) 
				{
					selIndices.push(i);
				}
				selectedIndices = selIndices;
				caretIndex = newCaretIndex;
				selChanged = true;
			} else 
			{
				selectedIndex = newCaretIndex;
				caretIndex = lastCaretIndex = newCaretIndex;
				selChanged = true;
			}
			if(selChanged) 
			{
				dispatchEvent(new Event(Event.CHANGE));
			}
			invalidate(InvalidationType.DATA);
		}
		
		/**
		 * 基于 labelField 和 labelFunction 属性检索渲染器将为给定数据对象显示的字符串。
		 * 注意：labelField 不在 labelFunction 属性设置为回调函数时使用。
		 * 参数
		 * item:Object — 要呈现的对象
		 * 返回
		 * String — 根据数据要显示的字符串。
		 */
		override public function itemToLabel(item:Object):String 
		{
			if (_labelFunction != null) 
			{
				return String(_labelFunction(item));
			} else  
			{
				return (item[_labelField]!=null) ? String(item[_labelField]) : "";
			}
		}
		/**
         * @private (protected)
		 */
		override protected function initializeAccessibility():void 
		{
			if (List.createAccessibilityImplementation != null) 
			{
				List.createAccessibilityImplementation(this);
			}
		}
	}
}
